<template>
  <van-sticky :offset-top="`${stickyOffsetTop}px`" @scroll="onStickyScroll">
    <div :class="{'is-fixed':isFixed}">
      <CNavBar :bars="bars" class="m_b5" @onChange="onNav"/>
      <SingleTags v-if="singleTags.length>0" @onChange="onSingleTagsChange" :data="singleTags"/>
    </div>
  </van-sticky>
  <div class="flex-column p_x10" v-if="lists.list&&lists.list.length>0">
    <van-list
        v-model:loading="listState.loading"
        :finished="listState.finished"
        :finished-text="listState.placeholder"
        @load="onLoad">
      <GoodItem
          :key="`good-item-${i}`"
          :merchant="item.merchant||{}"
          :data="item"
          :files="jsonParse(item.fileJson)"
          v-for="(item,i) of lists.list">
      </GoodItem>
    </van-list>
  </div>
  <DataNull v-else></DataNull>
</template>

<script lang="ts">
import {defineComponent} from "vue";
import CNavBar from "@/components/common/CNavBar.vue";
import SingleTags from "@/components/filterBar/SingleTags.vue";
import GoodItem from "@/components/goods/GoodItem.vue";
import DataNull from "@/components/dataNull/DataNull.vue";
import {useSticky} from "@/hooks/Sticky";
import {mapState, useStore} from "vuex";
import AlliancesEvent from "@/api/modules/AlliancesEvent";
import {deepClone, isEmpty} from "@/utils/helpers";

export default defineComponent({
  name: "Goods",
  components: {
    CNavBar,
    SingleTags,
    GoodItem,
    DataNull,
  },
  emits: [
    'onChangeHeight'
  ],
  props: {
    stickyOffsetTop: {
      type: Number,
      default: 0
    },
    keyword: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      lists: {
        list: [] as any[],
      },
      singleTags: [
        {label: '精选推荐', type: 'hot', order: 'desc'},
        {label: '距离最近', type: 'distance', order: 'asc'},
      ],
      bars: [],
      searchQuery: {
        sortType: 'hot',
        sortOrder: 'desc',
        tagCodes: [] as any[],
        pageLimit: 10,
        pageIndex: 2,
      },
      listState: {
        loading: false,
        finished: false,
        placeholder: '没有更多了',
      }
    }
  },
  computed: {
    ...mapState('personal', [
      'info'
    ])
  },
  watch: {
    searchQuery: {
      deep: true,
      handler(val) {
        this.getHomePage()
      }
    },
    keyword() {
      this.getHomePage()
    }
  },
  setup() {
    return {
      ...useSticky()
    }
  },
  async created() {
    const store = useStore();
    await store.dispatch('personal/getInfo')
    this.getTags();
    await this.getHomePage();

  },
  methods: {
    jsonParse(val?: string) {
      try {
        return JSON.parse(val || '')
      } catch (e) {
        return {}
      }
    },
    onSingleTagsChange({item}: any) {
      this.searchQuery.sortType = item.type
      this.searchQuery.sortOrder = item.order
      this.searchQuery.pageIndex = 1
    },
    onNav({item}: any) {
      if (isEmpty(item.code)) {
        if (!isEmpty(this.searchQuery.tagCodes)) {
          this.searchQuery.tagCodes = []
          this.searchQuery.pageIndex = 1
        }
      } else {
        if (!this.searchQuery.tagCodes.includes(item.code)) {
          this.searchQuery.tagCodes = [item.code]
          this.searchQuery.pageIndex = 1
        }
      }
    },
    onLoad() {
      this.searchQuery.pageIndex++;
    },
    // 获取商品标签
    getTags() {
      AlliancesEvent.listTag({
        allianceCode: this.info.leaderCode || '',
        allianceGroupCode: this.info.currentAllianceGroupCode || '',
      }).then(res => {
        const bars = (res.data || []).map((item: any) => {
          item.label = item.name;
          return item;
        })
        bars.unshift({label: '全部商品'})
        this.bars = bars;
      }).catch(console.log);
    },
    // 获取数据列表
    async getHomePage() {
      const searchQuery = deepClone(this.searchQuery)
      searchQuery.tagCodes = JSON.stringify(searchQuery.tagCodes);
      try {
        const {data, result}: any = await AlliancesEvent.homePage({
          ...searchQuery,
          keyword: this.keyword,
          alliancesCode: this.info.leaderCode || '',
          alliancesGroupCode: this.info.currentAllianceGroupCode || '',
        })
        if (result) {
          this.listState.finished = data.index >= data.page;
          if (data.index > 1) {
            const currentList = this.lists.list;
            data.list = [...currentList, ...(data.list || [])];
          }

          this.lists = data
        }
      } catch (e) {
        console.log(e)
      }
      this.listState.loading = false;

    }
  },

})
</script>

<style lang="less" scoped>
.is-fixed {
  background-color: #ffffff;
  padding-bottom: 8px;
  box-shadow: 0 0 3px #eeeeee;
}
</style>
